package com.ttbj.core.filter;

import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;
import com.ttbj.core.util.ResourceBundleUtils;

/**
 * 消费者白名单ip权限过滤
 * <p>
 * dubbo.properties文件中，需要配置以下两个参数：<br/>
 * 生效状态：dubbo.provider.auth.isenabled（0-不生效，1-生效）<br/>
 * 白名单ip：dubbo.provider.auth.ips（ip列表，用英文逗号“,”分开）
 * 
 * @author Daniel
 * @date 2017年3月28日 下午9:35:42
 * 
 */
public class DubboAuthFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private static final ResourceBundle bundle = ResourceBundleUtils.getBundle("dubbo");
	private final static String isEnabled = ResourceBundleUtils.getValue(bundle, "dubbo.provider.auth.isenabled");
	private final static String ipsString = ResourceBundleUtils.getValue(bundle, "dubbo.provider.auth.ips");

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		String loggerHeader = "消费者白名单ip权限过滤-";
		logger.debug("{}S", loggerHeader);
		String consumerIp = RpcContext.getContext().getRemoteHost();
		logger.debug("{}consumerIp={}", loggerHeader, consumerIp);
		if ("0".equals(isEnabled)) {
			logger.debug("{}已停用", loggerHeader);
			return invoker.invoke(invocation);
		}

		String[] ips = ipsString.split(",");
		for (String ip : ips) {
			if (ip.equals(consumerIp)) {
				return invoker.invoke(invocation);
			}
		}
		logger.error("{}consumerIp={}请求被禁止", loggerHeader, consumerIp);
		return new RpcResult(new RuntimeException(loggerHeader + consumerIp + "请求被禁止"));
	}
}
